﻿using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Collections.Generic;
using System.Configuration;
//using System.Linq;
using System.Text;

namespace WindowsFormsSM
{
    public  class SMEncryption
    {
        #region MyRegion
        //后端解析
        public static string SM2PubKey =""; //ConfigurationManager.AppSettings["setting:SM2PubKey"];
        public static string SM2PrivateKey =""; //ConfigurationManager.AppSettings["setting:SM2PriKey"];

        //前端（医院）
        public static string SM2PubKeyWeb = "";//ConfigurationManager.AppSettings["Web:SM2PubKey"];
        public static string SM2PrivateKeyWeb = "";//ConfigurationManager.AppSettings["Web:SM2PriKey"];

        private static string CredentialFormat = @"
                                                            <root>
	                                                            <org code=""{0}"">{1}</org>
	                                                            <visitor type=""{2}"" code=""{3}"" key=""{4}"">{5}</visitor>
                                                            </root>
                                                            ";
        
        #endregion

        //SM2 获取秘钥方法
        public static string SM2GetKey()
        {
            string priKey = string.Empty;
            string pubkey = string.Empty;
            var strkey = SM2Util.GenerateKeyPair();
            pubkey = strkey[0].ToUpper().ToString();
            priKey = strkey[1].ToUpper().ToString();
            return "pubKey:" + pubkey + "\r\n" + "priKey:" + priKey;
        }

    

        //SM4 获取秘钥方法
        /// <returns></returns>
        public static string Encrypt(ref string strCredential, ref string strKey, Credential credential)
        {
            string SM4Key = Guid.NewGuid().ToString();
            strKey = SM2EncryptBase64(SM4Key, SM2PubKeyWeb);
            strCredential = SM4EncryptBase64_ECB(CreateCredential(credential), SM4Key);
            return SM4Key;
        }

        /// <summary>
        /// 构造身份信息
        /// </summary>
        /// <returns></returns>
        public static string CreateCredential(Credential credential)
        {
            if (credential.Type == 1)
            {
                CredentialFormat = @"
                                <root>
	                                <org code=""{0}""></org>
	                                <visitor type=""{1}"" code=""{2}"" key=""{3}"" ip=""{4}""></visitor>
                                </root>
                                ";
                return string.Format(CredentialFormat, "xmjkwz",
                                credential.Type, credential.Code, credential.pwd, credential.IP);
            }
            else if (credential.Type == 2)
            {
                CredentialFormat = @"
                                                            <root>
	                                                            <org code=""{0}"">{1}</org>
	                                                            <visitor type=""{2}"" code=""{3}"" key=""{4}"" ip=""{5}"">{6}</visitor>
                                                            </root>
                                                            ";
                return string.Format(CredentialFormat, credential.OrgCode, credential.OrgName,
                "2", credential.Code, credential.pwd, credential.IP, "机构调阅");
            }
            else
            {
                CredentialFormat = @"
                                                            <root>
	                                                            <org code=""{0}"">{1}</org>
	                                                            <visitor type=""{2}"" code=""{3}"" key=""{4}"">{5}</visitor>
                                                            </root>
                                                            ";
            }
            return string.Format(CredentialFormat, "1", "龙岩市卫生局",
                "0", "administrator", "administrator", "管理员");
        }

        /// <summary>
        /// SM2加密 非对称
        /// </summary>
        /// <param name="strdata"></param>
        /// <param name="pubKey"></param>
        /// <returns></returns>

        public static string SM2EncryptBase64(string strdata, string pubKey)
        {
            return SM2Util.encryptBase64(strdata, pubKey.ToLower());
        }

        /// <summary>
        /// SM2 解密 非对称
        /// </summary>
        /// <param name="strdata"></param>
        /// <param name="priKey"></param>
        /// <returns></returns>

        public static string SM2DecryptBase64(string strdata, string priKey)
        {
            SM2 sm2 = new SM2(priKey.ToLower(), null);
            byte[] deCode = Base64.Decode(strdata);
            byte[] decryptText = sm2.deceypt(deCode);
            return Encoding.UTF8.GetString(decryptText);
        }

        /// <summary>
        /// SM4 加密 （对称）
        /// </summary>
        /// <param name="strdata"></param>
        /// <param name="Key"></param>
        /// <returns></returns>

        public static string SM4EncryptBase64_ECB(string strdata, string Key)
        {
            SM4Utils.secretKey = Key;
            SM4Utils.hexString = false;
            string ciphertext = SM4Utils.Encrypt_ECB(strdata);

            return ciphertext;
        }

        /// <summary>
        /// SM4 解密 （对称）
        /// </summary>
        /// <param name="strdata"></param>
        /// <param name="Key"></param>
        /// <returns></returns>

        public static string SM4DecryptBase64_ECB(string strdata, string Key)
        {
            SM4Utils.secretKey = Key;
            SM4Utils.hexString = false;
            string ciphertext = SM4Utils.Decrypt_ECB(strdata);
            return ciphertext;
        }
    }

    public class Credential
    {
        public string OrgCode { get; set; }
        public string OrgName { get; set; }
        public Int32 Type { get; set; }
        public string Code { get; set; }
        public string pwd { get; set; }
        public string IP { get; set; }
    }
}
